

(function($){

var	getList = function(me){
		return me.find("div.tabber:first>div:first");
	},

	getItems = function(me){
		return me.find(">input[type=hidden]:first");
	},

	refreshItems = function(e,ui){
		var list = getList(e.data),
			items = getItems(e.data),
			tmp = "";
		list.find("span:hidden").each( function(){
				tmp += $(this).html()+",";
			});
		items.val( tmp );
	},

	addList = function(me,new_atom_id, text){
		var cntnr = $("<div class='ui-state-default'>"),
			close = $("<button>Delete</button>");
			atomid = $("<span style='display: none'>"+new_atom_id+"</span>");
		close.bind("click", me, function(e){
									$(e.target).parent().remove();
									refreshItems(e);
								}).button({icons:{primary: "ui-icon-close"},text:false});
		getList(me).append( cntnr.append( close ).append( atomid ).append( text ) ).sortable("refresh");

	};

Core.ObjectTypes["div.Box_List_Edit"] = function(){
	var me = $(this),
		items = getItems(me).val().split(","),
		i=0,
		list=getList(me);
	// Add the feedback from the atom manager back to the list of selected atoms...
	me.find("div.tabber:first>div:eq(1)").find("div.atom_manager").bind("atom_selected", me,
										function(e,id, text){
											var i=getItems(e.data);
											addList(e.data,id,text);
											i.val( i.val()+","+id);
											return false;
										});

	// Make the list sortable...
	list.sortable()
		// bind the initialization event to it...
		.bind("append_on_init", me, function(e,data){
				// add the item to the list
				addList(e.data, data.atom_id, "["+data.type+"] "+data.title);
				return false;
			})
		// bind the refresh event to update the hidden input with the new sorting
		.bind("sortupdate", me, refreshItems);

	// Process all the items and load them (by loading title and type via AJAX)
	//if ( items[0] != "" ){
		for (i=0; i < items.length; i++){
			if ( items[i] != "" ){
				list.jsonRequest("MgmBoxes",
									{'action': "get",
									'id':items[i],
									'all':true},
								"append_on_init");
			}
		}
	//}
};

}(jQuery))
